<template>
  <div class="volunteer-center">
    <div class="header">
      <h2>志愿者中心</h2>
      <p v-if="isVolunteer" class="welcome-text">欢迎您，尊敬的志愿者！</p>
      <p v-else-if="volunteerStatus === 'pending'" class="pending-text">您的志愿者申请正在审核中</p>
      <p v-else-if="volunteerStatus === 'rejected'" class="rejected-text">您的志愿者申请未通过审核</p>
      <p v-else class="not-volunteer-text">您尚未成为志愿者，无法查看志愿者任务</p>
    </div>

    <!-- 志愿者状态提示 -->
    <div v-if="volunteerStatus === 'pending'" class="status-banner pending">
      <h3>⏳ 申请审核中</h3>
      <p>您的志愿者申请正在审核中，请耐心等待管理员审批</p>
    </div>

    <div v-if="volunteerStatus === 'rejected'" class="status-banner rejected">
      <h3>❌ 申请未通过</h3>
      <p>您的志愿者申请未通过审核，您可以重新提交申请</p>
      <button class="btn-reapply" @click="reapply">重新申请</button>
    </div>

    <!-- 志愿者专属内容 -->
    <div v-if="isVolunteer" class="volunteer-content">
      <!-- 任务筛选 -->
      <div class="filter-section">
        <div class="filter-group">
          <label>任务状态：</label>
          <select v-model="filterStatus" @change="filterActivities">
            <option value="">全部</option>
            <option value="open">可报名</option>
            <option value="applied">已报名</option>
            <option value="approved">已通过</option>
            <option value="rejected">未通过</option>
          </select>
        </div>
        <button class="refresh-btn" @click="fetchData">刷新</button>
      </div>

      <!-- 任务列表 -->
      <div class="activities-section">
        <h3>志愿者任务列表</h3>

        <div v-if="loading" class="loading-state">
          <p>加载中...</p>
        </div>

        <div v-else-if="filteredActivities.length > 0" class="activities-list">
          <div class="activity-card" v-for="activity in filteredActivities" :key="activity.activityId">
            <div class="activity-header">
              <h4 class="activity-title">{{ activity.title }}</h4>
              <span class="activity-status" :class="getEnrollStatus(activity.activityId)">
                {{ getEnrollStatusText(activity.activityId) }}
              </span>
            </div>

            <div class="activity-info">
              <div class="info-row">
                <label>活动描述：</label>
                <span class="activity-description">{{ activity.description }}</span>
              </div>
              <div class="info-row">
                <label>活动时间：</label>
                <span>{{ formatTimeRange(activity.startTime, activity.endTime) }}</span>
              </div>
              <div class="info-row">
                <label>活动地点：</label>
                <span>{{ activity.location }}</span>
              </div>
              <div class="info-row">
                <label>所需人数：</label>
                <span>{{ activity.recruitNum }} 人</span>
              </div>
              <div class="info-row">
                <label>已报名：</label>
                <span>{{ activity.recruitedNum }} 人</span>
              </div>
              <div class="info-row">
                <label>活动状态：</label>
                <span>{{ activity.status === 1 ? '招募中' : '已结束' }}</span>
              </div>
              <div v-if="activity.remark" class="info-row">
                <label>备注：</label>
                <span class="activity-remark">{{ activity.remark }}</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <button
                v-if="!hasApplied(activity.activityId) && activity.status === 1"
                class="btn-apply"
                @click="applyForActivity(activity)"
                :disabled="activity.recruitedNum >= activity.recruitNum"
              >
                {{ activity.recruitedNum >= activity.recruitNum ? '名额已满' : '报名参加' }}
              </button>

              <button
                v-if="hasApplied(activity.activityId) && getEnrollStatus(activity.activityId) === 'pending'"
                class="btn-cancel"
                @click="cancelApplication(activity)"
              >
                取消报名
              </button>

              <span v-if="getEnrollStatus(activity.activityId) === 'approved'" class="status-approved">
                ✅ 已通过
              </span>

              <span v-if="getEnrollStatus(activity.activityId) === 'rejected'" class="status-rejected">
                ❌ 未通过
              </span>

              <span v-if="activity.status !== 1" class="status-ended">
                ⏹️ 已结束
              </span>
            </div>
          </div>
        </div>

        <div v-else class="empty-state">
          <p>{{ filterStatus ? '没有符合条件的任务' : '暂无志愿者任务' }}</p>
        </div>
      </div>
    </div>

    <!-- 非志愿者提示 -->
    <div v-else-if="!volunteerStatus" class="non-volunteer-content">
      <div class="prompt-card">
        <h3>成为志愿者</h3>
        <p>要参与志愿者任务，您需要先申请成为志愿者并通过审核</p>
        <button class="btn-apply-volunteer" @click="goToApply">立即申请成为志愿者</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

interface VolunteerActivity {
  activityId: number
  title: string
  description: string
  startTime: string
  endTime: string
  location: string
  recruitNum: number
  recruitedNum: number
  status: number // 1: 招募中, 其他: 已结束
  remark?: string
}

interface VolunteerEnroll {
  enrollId: number
  volunteerId: number
  activityId: number
  enrollStatus: number // 0: 待审核, 1: 已通过, 2: 已拒绝
  enrollTime: string
}

const router = useRouter()

// 响应式数据
const volunteerStatus = ref('') // pending, approved, rejected, ''
const volunteerInfo = ref<any>(null)
const activities = ref<VolunteerActivity[]>([])
const enrollments = ref<VolunteerEnroll[]>([])
const loading = ref(false)
const filterStatus = ref('')

// 计算属性
const isVolunteer = computed(() => volunteerStatus.value === 'approved')

const filteredActivities = computed(() => {
  let filtered = activities.value

  if (filterStatus.value === 'open') {
    filtered = filtered.filter(activity =>
      activity.status === 1 && !hasApplied(activity.activityId)
    )
  } else if (filterStatus.value === 'applied') {
    filtered = filtered.filter(activity => hasApplied(activity.activityId))
  } else if (filterStatus.value === 'approved') {
    filtered = filtered.filter(activity => getEnrollStatus(activity.activityId) === 'approved')
  } else if (filterStatus.value === 'rejected') {
    filtered = filtered.filter(activity => getEnrollStatus(activity.activityId) === 'rejected')
  }

  return filtered
})

// 生命周期
onMounted(() => {
  fetchData()
})

// 获取所有数据
const fetchData = async () => {
  loading.value = true
  try {
    await checkVolunteerStatus()
    if (isVolunteer.value) {
      await Promise.all([fetchActivities(), fetchEnrollments()])
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 检查志愿者状态
const checkVolunteerStatus = async () => {
  try {
    const token = localStorage.getItem('token') || ''
    const userId = localStorage.getItem('userId')

    const response = await fetch(`http://localhost:8080/api/volunteer/user/${userId}`, {
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result = await response.json()
      console.log('志愿者状态响应:', result)

      if (result.success) {
        if (result.volunteer) {
          volunteerInfo.value = result.volunteer
          volunteerStatus.value = result.volunteer.status || ''
        } else {
          volunteerStatus.value = ''
        }
      }
    }
  } catch (error) {
    console.error('检查志愿者状态失败:', error)
    volunteerStatus.value = ''
  }
}

// 获取志愿者活动列表
const fetchActivities = async () => {
  try {
    const token = localStorage.getItem('token') || ''

    const response = await fetch('http://localhost:8080/va/all', {
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    if (response.ok) {
      const result = await response.json()
      console.log('活动列表响应:', result)
      activities.value = result.activities || []
    }
  } catch (error) {
    console.error('获取志愿者活动失败:', error)
    activities.value = []
  }
}

// 获取报名记录
const fetchEnrollments = async () => {
  try {
    const token = localStorage.getItem('token') || ''

    if (volunteerInfo.value && volunteerInfo.value.volunteerID) {
      const volunteerId = volunteerInfo.value.volunteerID

      const enrollResponse = await fetch(`http://localhost:8080/ve/byVolunteer?volunteerId=${volunteerId}`, {
        headers: {
          'token': token,
          'Content-Type': 'application/json'
        }
      })

      if (enrollResponse.ok) {
        const enrollResult = await enrollResponse.json()
        console.log('报名记录响应:', enrollResult)
        enrollments.value = enrollResult.data || []
      }
    }
  } catch (error) {
    console.error('获取报名记录失败:', error)
    enrollments.value = []
  }
}

// 报名参加活动
const applyForActivity = async (activity: VolunteerActivity) => {
  if (!confirm(`确定要报名参加"${activity.title}"吗？`)) return

  try {
    const token = localStorage.getItem('token') || ''

    const response = await fetch(`http://localhost:8080/ve/applyForActivity?activityId=${activity.activityId}`, {
      method: 'POST',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()
    console.log('报名响应:', result)

    if (result.success) {
      alert('报名成功！请等待审核')
      await fetchEnrollments() // 刷新报名记录
    } else {
      alert(result.message || '报名失败')
    }
  } catch (error) {
    console.error('报名失败:', error)
    alert('网络错误，请稍后重试')
  }
}

// 取消报名
const cancelApplication = async (activity: VolunteerActivity) => {
  if (!confirm(`确定要取消报名"${activity.title}"吗？`)) return

  try {
    const token = localStorage.getItem('token') || ''
    const enrollment = enrollments.value.find(e => e.activityId === activity.activityId)

    if (!enrollment) return

    const response = await fetch(`http://localhost:8080/ve/delete?enrollId=${enrollment.enrollId}`, {
      method: 'DELETE',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.success) {
      alert('取消报名成功')
      await fetchEnrollments() // 刷新报名记录
    } else {
      alert(result.message || '取消报名失败')
    }
  } catch (error) {
    console.error('取消报名失败:', error)
    alert('网络错误，请稍后重试')
  }
}

// 工具函数
const hasApplied = (activityId: number) => {
  return enrollments.value.some(e => e.activityId === activityId)
}

const getEnrollStatus = (activityId: number) => {
  const enrollment = enrollments.value.find(e => e.activityId === activityId)
  if (!enrollment) return ''

  const statusMap: { [number: string]: string } = {
    0: 'pending',
    1: 'approved',
    2: 'rejected'
  }
  return statusMap[enrollment.enrollStatus] || ''
}

const getEnrollStatusText = (activityId: number) => {
  const status = getEnrollStatus(activityId)
  const statusMap: { [string: string]: string } = {
    'pending': '审核中',
    'approved': '已通过',
    'rejected': '未通过'
  }
  return statusMap[status] || ''
}

const formatTime = (timeString: string) => {
  if (!timeString) return '-'
  return new Date(timeString).toLocaleString('zh-CN')
}

const formatTimeRange = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return '-'
  const start = new Date(startTime)
  const end = new Date(endTime)
  return `${start.toLocaleString('zh-CN')} - ${end.toLocaleString('zh-CN')}`
}

const filterActivities = () => {
  // 筛选逻辑已经在计算属性中处理
}

// 导航函数
const goToApply = () => {
  const event = new CustomEvent('navigate-to-volunteer')
  window.dispatchEvent(event)
}

const reapply = () => {
  goToApply()
}
</script>

<style scoped>
.volunteer-center {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  color: #2E7D32;
  font-size: 2rem;
  margin-bottom: 10px;
}

.welcome-text {
  color: #4CAF50;
  font-size: 1.1rem;
}

.pending-text {
  color: #FF9800;
  font-size: 1.1rem;
}

.rejected-text {
  color: #F44336;
  font-size: 1.1rem;
}

.not-volunteer-text {
  color: #666;
  font-size: 1.1rem;
}

.status-banner {
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  text-align: center;
}

.status-banner.pending {
  background: #FFF3E0;
  border: 1px solid #FFB74D;
}

.status-banner.rejected {
  background: #FFEBEE;
  border: 1px solid #EF5350;
}

.status-banner h3 {
  margin-bottom: 10px;
  color: #333;
}

.btn-reapply {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

.volunteer-content {
  width: 100%;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: bold;
  color: #333;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.refresh-btn {
  padding: 8px 16px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.activities-section h3 {
  color: #2E7D32;
  margin-bottom: 20px;
  font-size: 1.5rem;
}

.loading-state, .empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.activity-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.activity-title {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.activity-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
  font-weight: bold;
}

.activity-status.pending {
  background: #FFF3E0;
  color: #EF6C00;
}

.activity-status.approved {
  background: #E8F5E8;
  color: #2E7D32;
}

.activity-status.rejected {
  background: #FFEBEE;
  color: #C62828;
}

.activity-info {
  margin-bottom: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.info-row label {
  font-weight: bold;
  color: #333;
  min-width: 80px;
}

.activity-description, .activity-remark {
  flex: 1;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  align-items: center;
}

.btn-apply, .btn-cancel {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.btn-apply {
  background: #4CAF50;
  color: white;
}

.btn-apply:hover:not(:disabled) {
  background: #45a049;
}

.btn-apply:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.btn-cancel {
  background: #ff9800;
  color: white;
}

.btn-cancel:hover {
  background: #f57c00;
}

.status-approved {
  color: #2E7D32;
  font-weight: bold;
}

.status-rejected {
  color: #C62828;
  font-weight: bold;
}

.status-ended {
  color: #666;
  font-weight: bold;
}

.non-volunteer-content {
  text-align: center;
  padding: 40px 20px;
}

.prompt-card {
  background: linear-gradient(135deg, #E8F5E8, #C8E6C9);
  border: 1px solid #A5D6A7;
  border-radius: 12px;
  padding: 40px;
  max-width: 500px;
  margin: 0 auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.prompt-card h3 {
  color: #2E7D32;
  margin-bottom: 15px;
  font-size: 1.4rem;
}

.prompt-card p {
  color: #558B2F;
  margin-bottom: 20px;
  font-size: 1.1rem;
}

.btn-apply-volunteer {
  padding: 12px 24px;
  background: linear-gradient(to right, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-apply-volunteer:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>
